<?php 
// +----------------------------------------------------------------------
// | CRMUU-企微SCRM是专业的企业微信第三方源码系统.
// +----------------------------------------------------------------------
// | [CRMUU] Copyright (c) 2022 http://crmuu.com All rights reserved.
// +----------------------------------------------------------------------

namespace app\wework\model\user\client;
use think\facade\Db;
use think\facade\Session;

/**
* 客户列表类
**/
class CustomerModel {

	static public $wid;
	/**
	 * 获取用户列表数据
	 * @param $wid 账户id
	 * @param $page 页码
	 * @param $name 客户名称查询
	 * @param $department 员工部门查询
	 * @param $staff_id 员工查询
	 * @param $tags 标签查询
	 * @param $times 时间查询
	 * @param $add_way 渠道查询
	 * @param $gender 性别查询
	 * @param $status 状态查询
	 * @return 
	 */
 	static public function info($page,$name=NULL,$staff_id=NULL,$tags=NULL,$times=NULL,$add_way=NULL,$gender=NULL,$status=NULL,$size,$add_ways,$wid=NULL){
 		$wid = Session::get('wid')?:$wid;
		$res = Db::table('kt_wework_customer')
					->alias('c')
					->join(['kt_wework_staff'=>'w'],'c.staff_id = w.id');
		if($tags){
			foreach ($tags as $value){
				$where = [];
	            $where[] = ["c.tags","like","%\"{$value}\"%"];
				$res = $res->whereOr($where);
			}
			$where = [];
			$where["c.wid"] = $wid;
	 		if($staff_id) $where["c.staff_id"] = $staff_id;
	 		if($add_way === 0)$where["c.add_way"] = $add_way;
	 		if($add_way > 0)$where["c.add_way"] = $add_way;
	 		if($gender)$where["c.gender"] = $gender;
	 		if($gender === 0)$where["c.gender"] = $gender;
	 		if($status === 0)$where["c.status"] = $status;
			$res = $res->where($where);
		}else{
			$where["c.wid"] = $wid;
	 		if($staff_id) $where["c.staff_id"] = $staff_id;
	 		if($add_way === 0)$where["c.add_way"] = $add_way;
	 		if($add_way > 0)$where["c.add_way"] = $add_way;
	 		if($gender)$where["c.gender"] = $gender;
	 		if($gender === 0)$where["c.gender"] = $gender;
	 		if($status === 0)$where["c.status"] = $status;
			$res = $res->where($where);
		}
		if($status === 1) $res = $res->where('c.status', ">=","1");
		if($times) $res = $res->whereBetweenTime('c.createtime', $times[0], $times[1]);
		if($name) $res = $res->whereLike('c.name','%'.$name.'%');
		$res = $res->field("c.id,c.name,c.avatar,c.type,c.gender,c.status,c.staff_id,c.corp_name,c.remark,c.createtime,c.tags,c.add_way,w.name as staff_name,w.avatar as staff_avatar,c.score,c.integral");
					$data['count'] = $res->count();
					$data['item'] = $res->order('c.createtime desc')
								->json(["tags"])
								->filter(function($data) use($wid,$add_ways){
									$data["createtime"] = date("Y-m-d H:i:s",$data["createtime"]);
									$data["add_way"] = $data["add_way"]?$data["add_way"]:0;
									$data["add_way"] = $add_ways[$data["add_way"]];
									if(count($data["tags"]))$data["tags"] = Db::table("kt_wework_tag")->where(["wid"=>$wid,"tag_id"=>$data["tags"]])->field("tag_name,deleted")->select()->toArray();
									return $data;
								})
								->page($page,$size)
								->select()
								->toArray();
					$data['page'] = $page;
					$data['size'] = $size;
		return $data;
	}

	static public function setfield($wid){
		$res = Db::table("kt_wework_customer_setfield")->where(["wid"=>$wid,"type"=>1,"status"=>1])->column("name");
		$arr = [];
		foreach ($res as $value){
			if($value == "性别")$arr[] = ["gender","性别"];
			if($value == "年龄")$arr[] = ["age","年龄"];
			if($value == "生日")$arr[] = ["birthday","生日"];
			if($value == "描述")$arr[] = ["description","描述"];
			if($value == "邮箱")$arr[] = ["email","邮箱"];
			if($value == "QQ")$arr[] = ["qq","QQ"];
			if($value == "电话")$arr[] = ["remark_mobiles","电话"];
			if($value == "微博")$arr[] = ["weibo","微博"];
			if($value == "职位")$arr[] = ["position","职位"];
			if($value == "地址")$arr[] = ["address","地址"];
			if($value == "企业")$arr[] = ["corp_name","企业"];
			if($value == "来源")$arr[] = ["way","来源"];
		}
		return $arr;
	}

	/*
	* type 1 为增加，2为减少
	*/
	static public function updScore($ids,$size,$type){
		$res = Db::table('kt_wework_customer')->where(["id"=>$ids])->select()->toArray();
		if($type == 1){
			foreach ($res as $value){
				Db::table('kt_wework_customer')->where(["id"=>$value["id"]])->update(["score"=>$value["score"]+$size]);
			}
		}else{
			foreach ($res as $value){
				$set_size = $value["score"]-$size;
				if($set_size <= 0)$set_size = 0;
				Db::table('kt_wework_customer')->where(["id"=>$value["id"]])->update(["score"=>$set_size]);
			}
		}

		return $res;
	}

	static public function updIntegral($ids,$size,$type){
		$res = Db::table('kt_wework_customer')->where(["id"=>$ids])->select()->toArray();
		if($type == 1){
			foreach ($res as $value){
				Db::table('kt_wework_customer')->where(["id"=>$value["id"]])->update(["integral"=>$value["integral"]+$size]);
			}
		}else{
			foreach ($res as $value){
				$set_size = $value["integral"]-$size;
				if($set_size <= 0)$set_size = 0;
				Db::table('kt_wework_customer')->where(["id"=>$value["id"]])->update(["integral"=>$set_size]);
			}
		}

		return $res;
	}

	static public function customer($id){
		$wid = Session::get('wid');
 		$where["c.wid"] = $wid;
 		$where["c.id"] = $id;
		$res = Db::table('kt_wework_customer')
 						->alias('c')
 						->join(['kt_wework_staff'=>'w'],'c.staff_id = w.id')
 						->where($where)
 						->field("c.id,c.name,c.avatar,c.external_userid,c.type,c.gender,c.status,c.staff_id,c.corp_name,c.remark,c.createtime,c.tags,c.add_way,w.name as staff_name,w.avatar as staff_avatar")
 						// ->json(["tags"])
 						->find();
		return $res;
	}

	//详情
	static public function customerInfo($id){
		$wid = Session::get('wid');
		$res = Db::table('kt_wework_customer')->where(["id"=>$id])->json(["tags","remark_mobiles"])->field("id,name,avatar,age,gender,description,remark_mobiles,qq,enterprise,address,birthday,email,add_way,tags,external_userid,score,integral,type,external_userid,way,staff_id,remark,description")->find();
		$res["remark_mobiles"] = implode(",",$res["remark_mobiles"]);
		if(count($res["tags"])){
			$group_ids = array_column(Db::table("kt_wework_tag")->where(["tag_id"=>$res["tags"]])->field("group_id")->select()->toArray(),"group_id");
			$tags = [];
			foreach (array_unique($group_ids) as $key=>$value){
				$tags[$key]["group"] = Db::table("kt_wework_taggroup")->where(["group_id"=>$value])->field("group_id,group_name")->find();
				$tags[$key]["tag"] = Db::table("kt_wework_tag")->where(["tag_id"=>$res["tags"],"group_id"=>$value])->field("tag_name,deleted")->select()->toArray();
			}
			$res["tags"] = $tags;
		}
		$res["size"] = Db::table('kt_wework_customer')->where(["wid"=>$wid,"external_userid"=>$res["external_userid"]])->group("staff_id")->count();
		
		return $res;
	}

	static public function customerLists($ids){
		$res = Db::table('kt_wework_customer')->where(["id"=>$ids])->json(["tags","tag_info"])->select()->toArray();

		return $res;
	}

	static public function customerList($externalUserId){
		$wid = Session::get('wid');
 		$where["c.wid"] = $wid;
 		$where["c.external_userid"] = $externalUserId;
		$res = Db::table('kt_wework_customer')
 						->alias('c')
 						->join(['kt_wework_staff'=>'w'],'c.staff_id = w.id')
 						->where($where)
 						->field("c.external_userid,w.name,w.userid,w.id")
 						->select()
 						->toArray();
		return $res;
	}

	static public function customerAll($externalUserId,$staff_id=NULL){
		$wid = Session::get('wid');
 		$where["c.wid"] = $wid;
 		$where["c.external_userid"] = $externalUserId;
 		if($staff_id) $where["w.id"] = $staff_id;
		$res = Db::table('kt_wework_customer')
 						->alias('c')
 						->join(['kt_wework_staff'=>'w'],'c.staff_id = w.id')
 						->where($where)
 						->field("c.id,c.name,c.avatar,c.external_userid,c.type,c.gender,c.status,c.staff_id,c.corp_name,c.remark,c.createtime,c.tags,c.add_way,w.name as staff_name,w.avatar as staff_avatar,c.qq,c.enterprise,c.address,c.weibo")
 						->select()
 						->toArray();
		return $res;
	}


	/**
	* 所属员工
	*/
	static public function customerUser($externalUserId,$addWay){
		$wid = Session::get('wid');
 		$where["c.wid"] = $wid;
 		$where["c.external_userid"] = $externalUserId;
		$res = Db::table('kt_wework_customer')
 						->alias('c')
 						->join(['kt_wework_staff'=>'w'],'c.staff_id = w.id')
 						->where($where)
 						->field("w.name,w.avatar,c.createtime,c.add_way,w.id")
 						->filter(function($data) use($addWay){
 							$data["add_way"] = $addWay[$data["add_way"]];
 							$data["createtime"] = date("Y-m-d H:i:s",$data["createtime"]);
 							return $data;
 						})
 						->select()
 						->toArray();
		return $res;
	}

	/*
	* w.name 员工名称
	* c.name 客户名称
	*/
	static public function dynamicsAll($externalUserId,$staff_id=NULL){
		$wid = Session::get('wid');
 		$where["d.wid"] = $wid;
 		$where["d.customer_userid"] = $externalUserId;
 		if($staff_id) $where["w.id"] = $staff_id;
 		$ktime = 0;
 		$orders = 0;
		$res = Db::table('kt_wework_customer_dynamic')
 						->alias('d')
 						->join(['kt_wework_staff'=>'w'],'d.staff_id = w.id')
 						->join(['kt_wework_customer'=>'c'],'c.external_userid = d.customer_userid and c.staff_id = d.staff_id')
 						->where($where)
 						->field("w.name as staff_name,w.avatar as staff_avatar,d.type,d.glian_id,d.chat_id,d.content,c.name,c.avatar,d.create_time")
 						->filter(function($data)use($wid){
					    	$data["times"] = date("Y",strtotime($data["create_time"]))."年".date("m",strtotime($data["create_time"]))."月".date("d",strtotime($data["create_time"]))."日";
					    	$data["time"] = date("H:i",strtotime($data["create_time"]));
							if($data["chat_id"])$data["contents"] = Db::table("kt_wework_group")->where(["wid"=>$wid,"chat_id"=>$data["chat_id"]])->field("name")->find()["name"]?:"默认群聊";
							if($data["type"] == 5)$data["contents"] = Db::table("kt_wework_radar")->where(["wid"=>$wid,"id"=>$data["glian_id"]])->field(["title"])->find()["title"];
 							return $data;
 						})
 						->order('d.create_time DESC')
 						->select()
 						->toArray();
 		foreach ($res as $key=>$value){
 			if($ktime == date("Y-m-d",strtotime($value["create_time"]))){
				$res[$key]["orders"] = $orders;
			}else{
				$ktime = date("Y-m-d",strtotime($value["create_time"]));
				$orders+=1;
				$res[$key]["orders"] = $orders;
			}
 		}
		return $res;
	}

	static public function groupList($externalUserId,$staff_id=NULL){
		$wid = Session::get('wid');
 		$where["x.wid"] = $wid;
 		$where["x.userid"] = $externalUserId;
 		if($staff_id)$where["f.id"] = $staff_id;
		$res = Db::table('kt_wework_group_member')
						->alias('x')
 						->join(['kt_wework_group'=>'g'],'x.chat_id = g.chat_id')
 						->join(['kt_wework_staff'=>'f'],'g.staff_id = f.id')
 						->where($where)
 						->field("x.group_nickname,x.name,x.status,g.name,g.chat_id,f.name as staff_name,g.create_time,x.join_time")
 						->filter(function($data){
							$data["create_time"] = date("Y-m-d H:i:s",$data["create_time"]);
							$data["join_time"] = date("Y-m-d H:i:s",$data["join_time"]);
							$data["group_number"] = self::groupNumber($data["chat_id"]);
							return $data;
						})->select()
 						->toArray();
 		return $res;
	}

	static public function groupNumber($chat_id){
		$wid = Session::get('wid');
 		$where["wid"] = $wid;
 		$where["chat_id"] = $chat_id;
		$res = Db::table('kt_wework_group_member')
 						->where($where)
 						->count();
		return $res;
	}

	static public function tags($tags){ 
		$wid = Session::get('wid');
		$where["t.wid"] = $wid;
 		$where["t.tag_id"] = $tags;
 		$res = Db::table('kt_wework_tag')
 						->alias('t')
 						->join(['kt_wework_taggroup'=>'g'],'t.group_id = g.group_id')
 						->where($where)
 						->field("t.tag_name,g.group_name")
 						->select()
 						->toArray();
		return $res;
	}
	

	static public function setfieldList($id){
		$wid = Session::get('wid');
		$info = self::customerInfo($id);
		$staff_id = $info["staff_id"];
		$external_userid = $info["external_userid"];
		$res = Db::table("kt_wework_customer_setfield")
                ->where(["wid"=>$wid,"type"=>2,"status"=>1])
                ->order("sort desc")
                ->json(["content"])
                ->filter(function($data) use($wid,$staff_id,$external_userid){
                    $setfield_data = Db::table("kt_wework_customer_setfield_data")->where(["wid"=>$wid,"pid"=>$data["id"],"external_userid"=>$external_userid,"staff_id"=>$staff_id])->find();
                    $data["value"] = "";
                    if($setfield_data)$data["value"] = $setfield_data["content"];
                    return $data;
                })
                ->select()
                ->toArray();
        return $res;
	}

	static public function updUserFields($id,$field_id,$content){
		$wid = Session::get('wid');
		$info = self::customerInfo($id);
		$staff_id = $info["staff_id"];
		$external_userid = $info["external_userid"];
	 	$setfield_data = Db::table("kt_wework_customer_setfield_data")->where(["wid"=>$wid,"pid"=>$field_id,"external_userid"=>$external_userid,"staff_id"=>$staff_id])->find();
        if($setfield_data)Db::table("kt_wework_customer_setfield_data")->where(["wid"=>$wid,"pid"=>$field_id,"external_userid"=>$external_userid,"staff_id"=>$staff_id])->update(["content"=>$content]);
        if(!$setfield_data){
            $data["wid"] = $wid;
            $data["pid"] = $field_id;
            $data["external_userid"] = $external_userid;
            $data["content"] = $content;
            $data["staff_id"] = $staff_id;
            $data["ctime"] = date("Y-m-d H:i:s");
            Db::table("kt_wework_customer_setfield_data")->insertGetId($data);
        }

        return "1";
	}
}